<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <el-button type="primary" :icon="Plus" @click="toAdd"
            >添 加</el-button
          >
        </div>
      </template>
      <!-- 表格 -->
      <el-table
        v-loading="loading"
        :data="trademarkList"
        border
        style="width: 100%; margin-bottom: 20px"
      >
        <el-table-column type="index" align="center" label="序号" width="90" />
        <el-table-column prop="tmName" label="品牌名称" width="180" />
        <el-table-column label="品牌LOGO">
          <template v-slot="{ row }">
            <img :src="row.logoUrl" width="100" alt="" />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-tooltip
              class="box-item"
              effect="dark"
              content="修改"
              placement="top"
            >
              <el-button
                type="warning"
                size="small"
                :icon="Edit"
                @click="updateTrademark(row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="box-item"
              effect="dark"
              content="删除"
              placement="top"
            >
              <el-button
                type="danger"
                size="small"
                :icon="Delete"
                @click="deleteTrademark(row.id)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[3, 5, 10, 20]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <!-- 对话框 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="`${trademarkInfo.id ? '修改' : '添加'}品牌`"
    >
      <el-form :model="trademarkInfo" ref="trademarkRef" :rules="rules">
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input v-model="trademarkInfo.tmName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :action="`${BASE_URL}/admin/product/fileUpload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip text-red">图片大小不能超过2M</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="btnTrademark(trademarkRef)"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>


<script lang="ts">
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import type {
  TrademarkListModel,
  TrademarkModel,
} from "@/api/product/model/trademarkModel";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { onMounted, ref } from "vue";
import {
  reqGetTrademarkList,
  reqAddTrademark,
  reqUpdateTrademark,
  reqDeleteTrademarkInfo,
} from "@/api/product/trademark";
import type { UploadProps } from "element-plus";
import { reactive } from "vue";
export default {
  name: "tardemark",
};
</script>

<script lang="ts" setup>
const currentPage = ref(1); //当前页
const pageSize = ref(3); //每页显示条数值
const small = ref(false); //是否使用小型分页样式
const background = ref(false); //是否为分页按钮添加背景色
const disabled = ref(false); //是否禁用分页
const trademarkList = ref<TrademarkListModel>([]); //品牌列表数据
const total = ref(0); //数据的总条数
const loading = ref(false); //加载效果
const imageUrl = ref(""); //上传的图片地址
const trademarkRef = ref<FormInstance>();
// console.log("ii", import.meta);
const BASE_URL = import.meta.env.VITE_API_URL;
// console.log(BASE_URL);
//控制对话框弹出
const dialogFormVisible = ref(false);
//控制对话框中表单的属性
const form = ref({
  name: "",
  region: "",
  date1: "",
  date2: "",
  delivery: false,
  type: [],
  resource: "",
  desc: "",
});

//初始品牌信息
const initTrademark = () => {
  return {
    tmName: "", //品牌名称
    logoUrl: "", //品牌图片地址
  };
};
//品牌信息
const trademarkInfo = reactive<TrademarkModel>(initTrademark());

//书写校验规则
const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: "请添加品牌名称", trigger: "blur" },
    { min: 2, max: 6, message: "长度在2到6之间", trigger: "blur" },
  ],
  logoUrl: [
    { required: true, message: "请选择要上传的图片", trigger: "change" },
  ],
});

//图片上传成功之前的校验
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  const imgArr = ["image/jpeg", "image/png"];
  if (!imgArr.includes(rawFile.type)) {
    ElMessage.error('图片格式必须是"image/jpeg或image/png"!');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    console.log(rawFile.size / 1024 / 1024);
    ElMessage.error("图片大小不能超过2M!");
    return false;
  }
  return true;
};

//图片上传成功后，会执行handleAvatarSuccess这个函数中的代码
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  // console.log(response);
  imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  trademarkInfo.logoUrl = response.data;
  // 清除校验规则
  trademarkRef.value?.clearValidate(["logoUrl"]);
};

onMounted(() => {
  //1.获取品牌列表数据
  getTrademarkList();
});

//1.获取品牌列表数据
const getTrademarkList = async () => {
  loading.value = true; //显示loading效果
  const result = await reqGetTrademarkList(currentPage.value, pageSize.value);
  trademarkList.value = result.records;
  total.value = result.total;
  loading.value = false;
};

//当前页面的显示数量发生变化时
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  getTrademarkList();
};

//当前页发生变化时
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  getTrademarkList();
};

//处理`+添加`按钮中的确定按钮执行的功能
const btnTrademark = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      //如果有id 是修改，否则是添加
      if (trademarkInfo.id) {
        await reqUpdateTrademark(trademarkInfo);
      } else {
        await reqAddTrademark(trademarkInfo);
      }

      //消息弹出框
      ElMessage.success(`${trademarkInfo.id ? "更新" : "添加"}品牌成功了`);

      //重新获取品牌列表数据
      getTrademarkList();
      //关闭弹出框
      dialogFormVisible.value = false;
    } else {
      console.log("error submit!", fields);
    }
  });
};

//+添加按钮打开el-dialog弹出框执行的操作
const toAdd = () => {
  //清除校验规则  没有参数的时候，表示清除所有的校验规则
  trademarkRef.value?.clearValidate();
  //清空源对象中的属性值
  Object.assign(trademarkInfo, initTrademark());
  //图片地址设为空
  imageUrl.value = "";
  //打开el-dialog弹出框
  dialogFormVisible.value = true;
};

//修改
const updateTrademark = (row: TrademarkModel) => {
  //添加信息到trademarkInfo
  Object.assign(trademarkInfo, row);
  //图片地址重新赋值
  imageUrl.value = trademarkInfo.logoUrl;
  //弹出el-dialog框
  dialogFormVisible.value = true;
  // 清除校验规则  没有参数的时候，表示清除所有的校验规则
  trademarkRef.value?.clearValidate();
};

//删除一个trademark
const deleteTrademark = (id: number) => {
  ElMessageBox.confirm("您真的要删除此商品品牌吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await reqDeleteTrademarkInfo(id);
      ElMessage({
        type: "success",
        message: "删除成功",
      });

      // 还是要重新发送请求 获取数据
      getTrademarkList();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};
</script>




<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>